/**
 * 
 */
package com.baijia.tianxiao.connect.util;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
import com.baijia.tianxiao.connect.enums.CloseReasonEnum;
import com.baijia.tianxiao.connect.route.api.model.TianxiaoConnectSession;

/**
 * @author leiruiqi
 *
 */
@Service("tianxiaoInnerConnectUtil")
public class TianxiaoInnerConnectUtil {
	
	private static Logger logger = LoggerFactory.getLogger(TianxiaoInnerConnectUtil.class); 
	
	public static final ConcurrentHashMap<String,WebSocketSession> innerSessionMap = new ConcurrentHashMap<String,WebSocketSession>();  
	  
	public void addSession(String nameKey,WebSocketSession session){
		innerSessionMap.put(nameKey, session);	
	}
	
	public static WebSocketSession getSession(String nameKey){
		return innerSessionMap.get(nameKey);	
	}
	
	public static void closeSessionByReason(WebSocketSession session,CloseReasonEnum reason,String message){
		
		try {
			if(StringUtils.isNoneBlank(message)){
				session.sendMessage(new TextMessage(message));
			}
			
			session.close(CloseStatus.NORMAL.withReason(reason.name()));
		} catch (Exception e) {
			logger.error("close session exception",e);
		}	
	}
	
	
	public WebSocketSession removeSession(String nameKey){
		WebSocketSession session =  innerSessionMap.remove(nameKey);
		return session;
	}
	
	
	public static String connectionSesion2JsonStr(TianxiaoConnectSession connectSession){
		String jsonStr = JSON.toJSONString(connectSession);
		return jsonStr;
	}
	
	public static String createTxSessionKey(String domain,String bizType){
		
		if(StringUtils.isBlank(domain)||StringUtils.isBlank(bizType)){
			return null;
		}
		
		String websocket_username = domain+"-" + bizType;
		
		return websocket_username;
	}
	
	public static ConcurrentHashMap<String,WebSocketSession> getTianxiaoSessionMap(){
		return innerSessionMap;
	}
	
	public static Boolean containSession(String sessionKey){
		return innerSessionMap.containsKey(sessionKey);
	}
	
}
